package com.mindskip.xzs.Genetic;

import com.mindskip.xzs.domain.ExamPaper;
import com.mindskip.xzs.domain.ExamPaperDto;
import com.mindskip.xzs.domain.ExamPaperQuestionCustomerAnswer;
import com.mindskip.xzs.domain.Question;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class ExamPaperGenerator {

    private List<Question> questions;
    private ExamPaperDto examPaper;

    public ExamPaperGenerator(List<Question> questions, ExamPaperDto examPaper) {
        this.questions = questions;
        this.examPaper = examPaper;
    }

    // 生成试卷的方法
    public ExamPaperDto generateExamPaper() {
        List<Question> selectedQuestions = selectQuestions();
        fillExamPaper(selectedQuestions);
        return examPaper;
    }

    // 选择题目
    public List<Question> selectQuestions() {
        // 计算每道题目的适应度，这里简单地假设适应度与题目的难度成正比
        List<Double> fitnessScores = calculateFitnessScores(questions);

        // 使用轮盘赌选择法选择题目
        List<Question> selectedQuestions = new ArrayList<>();
        Random random = new Random();
        double totalFitness = fitnessScores.stream().mapToDouble(Double::doubleValue).sum();

        for (int i = 0; i < examPaper.getQuestionCount(); i++) {
            double r = random.nextDouble() * totalFitness;
            double sum = 0;
            for (int j = 0; j < questions.size(); j++) {
                sum += fitnessScores.get(j);
                if (sum >= r) {
                    selectedQuestions.add(questions.get(j));
                    break;
                }
            }
        }

        return selectedQuestions;
    }

    private List<Double> calculateFitnessScores(List<Question> questions) {
        // 这里简单地假设适应度与题目的难度成正比
        List<Double> fitnessScores = new ArrayList<>();
        for (Question question : questions) {
            double fitness = calculateFitness(question); // 计算题目的适应度
            fitnessScores.add(fitness);
        }
        return fitnessScores;
    }

    private double calculateFitness(Question question) {
        // 这里可以根据题目的难度、类型、得分等属性来计算题目的适应度
        // 适应度可以根据具体需求设计，例如难度越高适应度越低，得分越高适应度越高等
        // 这里简单地假设适应度与题目的难度成正比
        return question.getDifficult();
    }

    // 填充试卷
    public void fillExamPaper(List<Question> selectedQuestions) {
        // 将选中的题目填充到试卷中
        List<ExamPaperQuestionCustomerAnswer> examPaperQuestions = new ArrayList<>();
        for (Question question : selectedQuestions) {
            ExamPaperQuestionCustomerAnswer examPaperQuestion = new ExamPaperQuestionCustomerAnswer();
            examPaperQuestion.setQuestionId(question.getId());
            examPaperQuestion.setExamPaperId(examPaper.getId());
            // 可以根据需要设置其他属性
            examPaperQuestions.add(examPaperQuestion);
        }
        // 将填充好的题目列表设置到试卷中
        examPaper.setExamPaperQuestionCustomerAnswers(examPaperQuestions);
    }

    // 其他辅助方法可以根据需要添加
}